﻿#region summary

// Copyright (c)  MOKEYISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

#endregion

using NSQL.Expressions;
using NSQL.Generator;

namespace NSQL.Statements.SelectStatements
{
    public class SelectStatement : ISelectStatement
    {
        private SortingCollection _order;
        private GroupCollection _groupClause;
        
        /// <summary>
        /// With Statement
        /// </summary>
        public FactoringSelectStatementCollection WithStatements { get; set; } =
            new FactoringSelectStatementCollection();

        /// <summary>
        /// Selected elements
        /// </summary>
        public SelectElementCollection Elements { get; } = new SelectElementCollection();

        public TableSourceCollection TableSources { get; } = new TableSourceCollection();

        public ILogicalExpression Condition { get; set; }

        public GroupCollection GroupClause => _groupClause ?? (_groupClause = new GroupCollection());

        public SortingCollection Order => _order ?? (_order = new SortingCollection());

        public int Skip { get; set; }
        public int Limit { get; set; }

        public bool CanOptimized =>
            Elements.Count == 1 && TableSources.Count == 1 &&
            Elements[0] == SelectElement.Asterisk  &&
            TableSources[0] is ISelectStatement && Join is null &&
            Skip <= 0 && Limit <= 0 &&
            (_order == null || _order.Count == 0) &&
            (_groupClause == null || _groupClause.Count == 0 && _groupClause.Having is null);

        /// <inheritdoc />
        public string Alias { get; set; }

        /// <inheritdoc />
        public JoinNode Join { get; set; }

        public bool IsDual { get; } = false;

        public string Accept(ISqlGenerator generator) => generator.Generate(this);
        public object Tag { get; set; }
    }
}